/// 对话列表项组件
/// 显示对话联系人信息和最后一条消息
library;
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:chat_project/config/theme_config.dart';
import 'package:chat_project/models/conversation_model.dart';
import 'package:chat_project/models/message_model.dart';

class ConversationListItem extends StatelessWidget {
  final Conversation conversation;
  final VoidCallback onTap;
  final bool isSelected;
  
  const ConversationListItem({
    super.key,
    required this.conversation,
    required this.onTap,
    this.isSelected = false,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: ThemeConfig.paddingRegular,
          vertical: ThemeConfig.paddingRegular,
        ),
        decoration: BoxDecoration(
          color: isSelected 
              ? ThemeConfig.primaryColor.withOpacity(0.1) 
              : Colors.transparent,
          border: Border(
            bottom: BorderSide(
              color: Colors.grey.shade200,
              width: 0.5,
            ),
          ),
        ),
        child: Row(
          children: [
            // 头像和在线状态
            _buildAvatar(),
            const SizedBox(width: ThemeConfig.paddingRegular),
            
            // 聊天信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 用户名和时间
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        conversation.contact.username,
                        style: const TextStyle(
                          fontSize: ThemeConfig.fontSizeMedium,
                          fontWeight: FontWeight.bold,
                          color: ThemeConfig.textPrimaryColor,
                        ),
                      ),
                      Text(
                        _formatTime(conversation.updatedAt),
                        style: const TextStyle(
                          fontSize: ThemeConfig.fontSizeSmall,
                          color: ThemeConfig.textSecondaryColor,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  
                  // 最后一条消息和未读数
                  Row(
                    children: [
                      // 最后一条消息
                      Expanded(
                        child: conversation.lastMessage != null
                            ? _buildLastMessage(conversation.lastMessage!)
                            : const SizedBox(),
                      ),
                      
                      // 未读消息数
                      if (conversation.unreadCount > 0) ...[
                        const SizedBox(width: 8),
                        _buildUnreadBadge(conversation.unreadCount),
                      ],
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  // 构建头像
  Widget _buildAvatar() {
    return Stack(
      children: [
        // 头像
        CircleAvatar(
          radius: 24,
          backgroundColor: ThemeConfig.primaryColor.withOpacity(0.1),
          foregroundImage: NetworkImage(
            conversation.contact.avatar.startsWith('http')
                ? conversation.contact.avatar
                : 'http://10.0.2.2:5000${conversation.contact.avatar}',
          ),
          onForegroundImageError: (_, __) {},
          child: Text(
            conversation.contact.username.isNotEmpty
                ? conversation.contact.username.substring(0, 1).toUpperCase()
                : '?',
            style: const TextStyle(
              fontSize: ThemeConfig.fontSizeLarge,
              color: ThemeConfig.primaryColor,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        
        // 在线状态指示器
        if (conversation.contact.isOnline)
          Positioned(
            right: 0,
            bottom: 0,
            child: Container(
              width: 14,
              height: 14,
              decoration: BoxDecoration(
                color: ThemeConfig.successColor,
                border: Border.all(
                  color: Colors.white,
                  width: 2,
                ),
                shape: BoxShape.circle,
              ),
            ),
          ),
      ],
    );
  }
  
  // 构建最后一条消息
  Widget _buildLastMessage(Message message) {
    // 根据消息类型显示不同内容
    String messageText;
    
    switch (message.type) {
      case MessageType.image:
        messageText = '[图片]';
        break;
      case MessageType.file:
        messageText = '[文件]';
        break;
      case MessageType.audio:
        messageText = '[语音]';
        break;
      case MessageType.text:
      default:
        messageText = message.content;
    }
    
    return Text(
      messageText,
      style: TextStyle(
        fontSize: ThemeConfig.fontSizeSmall,
        color: conversation.unreadCount > 0
            ? ThemeConfig.textPrimaryColor
            : ThemeConfig.textSecondaryColor,
        fontWeight: conversation.unreadCount > 0
            ? FontWeight.bold
            : FontWeight.normal,
        overflow: TextOverflow.ellipsis,
      ),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }
  
  // 构建未读消息数量显示
  Widget _buildUnreadBadge(int count) {
    return Container(
      width: 20,
      height: 20,
      alignment: Alignment.center,
      decoration: const BoxDecoration(
        color: ThemeConfig.errorColor,
        shape: BoxShape.circle,
      ),
      child: Text(
        count > 99 ? '99+' : '$count',
        style: const TextStyle(
          color: Colors.white,
          fontSize: 10,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
  
  // 格式化时间
  String _formatTime(DateTime dateTime) {
    final now = DateTime.now();
    
    if (dateTime.year == now.year && 
        dateTime.month == now.month && 
        dateTime.day == now.day) {
      // 今天
      return DateFormat('HH:mm').format(dateTime);
    } else if (dateTime.year == now.year && 
               dateTime.month == now.month && 
               dateTime.day == now.day - 1) {
      // 昨天
      return '昨天';
    } else if (dateTime.year == now.year) {
      // 今年
      return DateFormat('MM-dd').format(dateTime);
    } else {
      // 去年
      return DateFormat('yyyy-MM-dd').format(dateTime);
    }
  }
} 